package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/chromedp/chromedp"
)
func RunWithTimeOut(ctx *context.Context, timeout time.Duration, tasks chromedp.Tasks) chromedp.ActionFunc {
	return func(ctx context.Context) error {
		timeoutContext, cancel := context.WithTimeout(ctx, timeout * time.Second)
		defer cancel()
		return tasks.Do(timeoutContext)
	}
}

func GetHttpHtmlContent(url string, selector string, sel interface{}) (string, error) {

	options := []chromedp.ExecAllocatorOption{
		chromedp.Flag("headless", false), // debug使用
		//chromedp.Flag("blink-settings", "imagesEnabled=false"),
		chromedp.Flag("remote-debugging-port", "9222"),
		chromedp.UserAgent(`Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36`),
	}
	//初始化参数，先传一个空的数据
	options = append(chromedp.DefaultExecAllocatorOptions[:], options...)

	c, _ := chromedp.NewExecAllocator(context.Background(), options...)

	// create context
	chromeCtx, cancel := chromedp.NewContext(c, chromedp.WithLogf(log.Printf))
	// 执行一个空task, 用提前创建Chrome实例
	err:=chromedp.Run(chromeCtx, make([]chromedp.Action, 0, 1)...)
	fmt.Println("err=",err)

	//创建一个上下文，超时时间为40s
	timeoutCtx, cancel := context.WithTimeout(chromeCtx, 40*time.Second)
	defer cancel()


	var htmlContent string
	err = chromedp.Run(
		timeoutCtx,
		//chromedp.Click("document.querySelector('.Modal-closeButton')",chromedp.ByJSPath),
		chromedp.Navigate(url),
		//chromedp.WaitVisible(sel),
		chromedp.OuterHTML(sel, &htmlContent, chromedp.ByJSPath),
		chromedp.Sleep(5*time.Second),
	)
	if err != nil {
		fmt.Printf("Run err : %v\n", err)
		return "", err
	}
	return htmlContent, nil
}

func main() {
	url:=`https://www.zhihu.com/people/xiao-hui-68-47/posts?page=1`

	s,_:=GetHttpHtmlContent(url,`.Pagination`,`document.querySelector("#Profile-posts")`)
	fmt.Println(s)

}